/* eslint-disable react/jsx-indent */
import React from 'react';
import { DownOutlined, EditOutlined, UpOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import {
  Card,
  Button,
  Spin,
  Timeline,
  Divider,
  Steps,
  Modal,
  Input,
  Select,
  message,
} from 'antd';
import { connect } from 'dva';
import router from 'umi/router';
import moment from 'moment';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import FooterToolbar from '@/components/FooterToolbar';
import DescriptionList from '@/components/DescriptionList';

const { Description } = DescriptionList;
const { Step } = Steps;
const { TextArea } = Input;
const FormItem = Form.Item;
const { Option } = Select;

@connect(({ addemprec, loading, publicdata }) => ({
  loading: loading.effects['addemprec/getEmpContactDetail'],
  addemprec,
  empContactList: addemprec.empContactList, // 员工联系详情
  dictCode: publicdata.dictCode,
}))
@Form.create()
class BasicForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      recvOrdAddTaskId: null,
      contactModal: false,
      remarkModal: false,
      isEdit: false,
      insIdeData: [], // 缴费人员类别
      insIde: '', // 缴费人员类别id
      contactCode: null,
      remarkCode: null,
      defaultConcatList: [],
      isExpandCollapse: true,
    };
    // 联系记录模态框布局
    this.formItemLayoutModal = {
      labelCol: { md: { span: 5 } },
      wrapperCol: { md: { span: 17, offset: 0 } },
    };
    // 办理备注模态框布局
    this.formItemRemarkModal = {
      labelCol: { md: { span: 6 } },
      wrapperCol: { md: { span: 17, offset: 0 } },
    };
  }

  componentDidMount() {
    const {
      dispatch,
      location: { query },
    } = this.props;
    // 获取字典
    dispatch({
      type: 'publicdata/fetchDictCode',
      payload: ['CONTACTWAY'],
    });
    // 获取员工联系详情信息
    dispatch({
      type: 'addemprec/getEmpContactDetail',
      payload: {
        recvOrdAddTaskId: query.recvOrdAddTaskId,
      },
      callback: data => {
        if (data.contRecDtoList) {
          if (data.contRecDtoList.length > 2) {
            const arr = data.contRecDtoList.slice(data.contRecDtoList.length - 2);
            this.setState({ defaultConcatList: arr });
          } else {
            this.setState({ defaultConcatList: data.contRecDtoList });
          }
        }
        if (data.insIdeFlag && data.insIdeFlag === 1) {
          // 获取缴费人员类别信息
          dispatch({
            type: 'addemprec/getInsIdeList',
            payload: {
              areaId: query.areaId,
            },
            callback: response => {
              if (response.success) {
                this.setState({
                  insIdeData: response.data,
                });
              } else {
                message.warning(response.message || '获取缴费人员类别失败：服务器端错误');
              }
            },
          });
        }
      },
    });
    this.setState({ recvOrdAddTaskId: query.recvOrdAddTaskId });
  }

  // 缴费人员类别选中
  insIdeChange = value => {
    this.setState({ insIde: value });
  };

  // 点击编辑缴费人员类别
  editContributorCategory = () => {
    this.setState({ isEdit: true });
  };

  // 保存缴费人员类别
  saveContributorCategory = () => {
    this.setState({ isEdit: false });
    const { dispatch } = this.props;
    const { recvOrdAddTaskId, insIde } = this.state;
    dispatch({
      type: 'addemprec/updateInsIde',
      payload: {
        recvOrdAddTaskId,
        insIde,
      },
      callback: response => {
        if (response.success) {
          message.success('修改成功！');
          dispatch({
            type: 'addemprec/getEmpContactDetail',
            payload: {
              recvOrdAddTaskId,
            },
          });
        } else {
          message.warning(response.message || '修改缴费人员类别失败：服务器端错误');
        }
      },
    });
  };

  // 打开联系记录弹框
  openContactModal = contactCode => {
    const { form } = this.props;
    form.resetFields(['entryContactType', 'entryContent']);
    this.setState({ contactModal: true, contactCode });
  };

  // 打开办理备注弹框
  openRemarkModal = remarkCode => {
    const { form } = this.props;
    form.resetFields(['insIde', 'hdlDesc']);
    this.setState({ remarkModal: true, remarkCode });
  };

  // 关闭弹框
  hideModal = () => {
    this.setState({
      contactModal: false,
      remarkModal: false,
    });
  };

  // 联系记录--提交
  contactSubmit = () => {
    const { dispatch, form } = this.props;
    const { recvOrdAddTaskId, contactCode } = this.state;
    form.validateFields(['entryContactType', 'entryContent'], (err, fieldsValue) => {
      if (err) return;
      dispatch({
        type: 'addemprec/insertEmpContact',
        payload: {
          entryContent: fieldsValue.entryContent, // 联系内容
          entryContactType: fieldsValue.entryContactType, // 联系方式
          recvOrdAddTaskId,
          entryContact: contactCode, // 入职联系节点状态
        },
        callback: response => {
          if (response.success) {
            message.success('提交成功！');
            dispatch({
              type: 'addemprec/getEmpContactDetail',
              payload: {
                recvOrdAddTaskId,
              },
              callback: data => {
                if (data.contRecDtoList) {
                  if (data.contRecDtoList.length > 2) {
                    const arr = data.contRecDtoList.slice(data.contRecDtoList.length - 2);
                    this.setState({ defaultConcatList: arr });
                  } else {
                    this.setState({ defaultConcatList: data.contRecDtoList });
                  }
                }
              },
            });
            this.setState({ contactModal: false });
          } else {
            message.warning(response.message || '提交数据：服务器端错误');
          }
        },
      });
    });
  };

  // 办理备注--提交
  remarkSubmit = () => {
    const { dispatch, form } = this.props;
    const { recvOrdAddTaskId, remarkCode } = this.state;
    form.validateFields(['insIde', 'hdlDesc'], (err, fieldsValue) => {
      if (err) return;
      dispatch({
        type: 'addemprec/insertEmpContact',
        payload: {
          insIde: fieldsValue.insIde || null,
          hdlDesc: fieldsValue.hdlDesc,
          recvOrdAddTaskId,
          hdlStatus: remarkCode, // 办理节点状态
        },
        callback: response => {
          if (response.success) {
            message.success('提交成功！');
            dispatch({
              type: 'addemprec/getEmpContactDetail',
              payload: {
                recvOrdAddTaskId,
              },
            });
            this.setState({ remarkModal: false });
          } else {
            message.warning(response.message || '提交数据：服务器端错误');
          }
        },
      });
    });
  };

  // 查看更多（展开）
  moreExpandList = () => {
    const { empContactList } = this.props;
    this.setState({ defaultConcatList: empContactList.contRecDtoList, isExpandCollapse: false });
  };

  // 收起
  moreCollapseList = () => {
    const { empContactList } = this.props;
    const newArr = empContactList.contRecDtoList.slice(empContactList.contRecDtoList.length - 2);
    this.setState({ defaultConcatList: newArr, isExpandCollapse: true });
  };

  render() {
    const {
      loading,
      form: { getFieldDecorator },
      empContactList,
      dictCode,
    } = this.props;
    const {
      isEdit,
      insIdeData,
      defaultConcatList,
      isExpandCollapse,
      contactModal,
      remarkModal,
    } = this.state;
    return (
      <PageHeaderWrapper>
        <Spin tip="Loading..." spinning={loading}>
          {/* 员工联系 */}
          <Card
            title={<span style={{ fontWeight: 'bolder' }}>员工联系</span>}
            style={{ border: 'none', marginBottom: 16 }}
          >
            <DescriptionList>
              <Description term="姓名">{empContactList.empName || '--'}</Description>
              <Description term="电话">{empContactList.mobile || '--'}</Description>
              {empContactList.insIdeFlag && empContactList.insIdeFlag === 1 ? (
                <div>
                  {!isEdit ? (
                    <Description term="缴费人员类别">
                      {empContactList.insIdeName || '--'}
                      <EditOutlined
                        onClick={() => this.editContributorCategory()}
                        style={{ fontSize: 16, color: '#1890FF', marginLeft: 5, cursor: 'pointer' }} />
                    </Description>
                  ) : (
                    <Description term="缴费人员类别">
                      <Select
                        placeholder="请选择"
                        onChange={this.insIdeChange}
                        style={{ width: 180, marginRight: 8 }}
                      >
                        {insIdeData
                          ? insIdeData.map(item => (
                              <Option key={item.ideId} value={item.ideId}>
                                {item.ideName}
                              </Option>
                            ))
                          : null}
                      </Select>
                      <a onClick={() => this.saveContributorCategory()}>保存</a>
                    </Description>
                  )}
                </div>
              ) : null}
            </DescriptionList>
            <Divider dashed />
            <div>
              <h4 style={{ fontWeight: 900 }}>入职联系</h4>
              <Steps style={{ width: '90%', margin: '24px auto' }} progressDot>
                {empContactList.contactList &&
                  empContactList.contactList.map(item => (
                    <Step
                      title={item.name}
                      description={
                        item.contactStatus === 1 ? (
                          <div>
                            <span
                              style={{
                                fontSize: '14px',
                                color: '#999',
                                width: 150,
                                display: 'inline-block',
                              }}
                            >
                              {item.operTime && moment(item.operTime).format('YYYY-MM-DD HH:mm:ss')}
                            </span>
                          </div>
                        ) : (
                          <div>
                            <span
                              style={{
                                fontSize: '14px',
                                color: '#1890FF',
                                width: 150,
                                display: 'inline-block',
                                cursor: 'pointer',
                              }}
                              onClick={() => this.openContactModal(item.contactCode)}
                            >
                              {item.name === '联系中' ? '标记联系中' : '标记联系完成'}
                            </span>
                          </div>
                        )
                      }
                      status={item.contactStatus === 1 ? 'finish' : 'wait'}
                    />
                  ))}
              </Steps>
            </div>
            <div style={{ marginTop: 48 }}>
              <h4 style={{ fontWeight: 900 }}>入职办理</h4>
              <Steps style={{ width: '90%', margin: '24px auto' }} progressDot>
                {empContactList.remarkList &&
                  empContactList.remarkList.map(item => (
                    <Step
                      title={item.name}
                      description={
                        item.remarkStatus === 1 ? (
                          <div>
                            <span
                              style={{
                                fontSize: '14px',
                                color: '#999',
                                width: 150,
                                display: 'inline-block',
                              }}
                            >
                              {item.operTime && moment(item.operTime).format('YYYY-MM-DD HH:mm:ss')}
                            </span>
                          </div>
                        ) : (
                          <div>
                            <span
                              style={{
                                fontSize: '14px',
                                color: '#1890FF',
                                width: 150,
                                display: 'inline-block',
                                cursor: 'pointer',
                              }}
                              onClick={() => this.openRemarkModal(item.remarkCode)}
                            >
                              {item.name === '材料不完整' ? '标记材料不完整' : '标记办理完成'}
                            </span>
                          </div>
                        )
                      }
                      status={item.remarkStatus === 1 ? 'finish' : 'wait'}
                    />
                  ))}
              </Steps>
            </div>
            <Divider dashed />
            <div style={{ width: '90%', margin: '0 auto' }}>
              <p style={{ color: '#999', fontSize: 14 }}>
                注：实际操作中可一次即可联系完成或办理完成，可直接点击标记联系完成或标记办理完成；如果没有标记联系完成或标记办理完成时做回单操作，系统会自动在回单的同时标记联系完成和办理完成
              </p>
            </div>
          </Card>
          {/* 联系记录 */}
          <Card
            title={<span style={{ fontWeight: 'bolder' }}>联系记录</span>}
            style={{ border: 'none', marginBottom: 16 }}
            extra={
              empContactList.contRecDtoList &&
              empContactList.contRecDtoList.length && (
                <a onClick={() => this.openContactModal()}>新增</a>
              )
            }
          >
            {(defaultConcatList &&
              defaultConcatList.length &&
              defaultConcatList.map((item, index) => (
                <div>
                  {index > 0 && <Divider dashed />}
                  <DescriptionList>
                    <Description term="联系方式">{item.contactInfo || '--'}</Description>
                    <Description term="联系电话">{item.contactMobile || '--'}</Description>
                    <Description term="联系人">{item.contactPer}</Description>
                    <Description term="联系时间">
                      {item.contactTime
                        ? moment(item.contactTime).format('YYYY-MM-DD HH:mm:ss')
                        : '--'}
                    </Description>
                    <Description term="联系内容">
                      <span dangerouslySetInnerHTML={{ __html: item.remark || '--' }} />
                    </Description>
                  </DescriptionList>
                </div>
              ))) ||
              '暂无数据'}
            {empContactList.contRecDtoList && empContactList.contRecDtoList.length > 2 && (
              <div>
                {isExpandCollapse ? (
                  <p
                    style={{ textAlign: 'center', marginTop: 16, cursor: 'pointer' }}
                    onClick={() => this.moreExpandList()}
                  >
                    查看更多
                    <DownOutlined style={{ fontSize: 12, marginLeft: 3 }} />
                  </p>
                ) : (
                  <p
                    style={{ textAlign: 'center', marginTop: 16, cursor: 'pointer' }}
                    onClick={() => this.moreCollapseList()}
                  >
                    收起
                    <UpOutlined style={{ fontSize: 12, marginLeft: 3 }} />
                  </p>
                )}
              </div>
            )}
          </Card>
          {/* 办理备注 */}
          <Card
            title={<span style={{ fontWeight: 'bolder' }}>办理备注</span>}
            style={{ border: 'none', marginBottom: 16 }}
            extra={
              empContactList.handDto &&
              empContactList.handDto.length && <a onClick={() => this.openRemarkModal()}>新增</a>
            }
          >
            {(empContactList.handDto && empContactList.handDto.length && (
              <Timeline>
                {empContactList.handDto.map(item => (
                  <Timeline.Item>
                    <p style={{ float: 'left', margin: '0 15px 0 20px' }}>
                      {item.operTime && moment(item.operTime).format('YYYY-MM-DD HH:mm:ss')}
                    </p>
                    <p style={{ float: 'left', margin: '0 20px 0 15px' }}> {item.handPer} </p>
                    <p> {item.content} </p>
                  </Timeline.Item>
                ))}
              </Timeline>
            )) ||
              '暂无数据'}
          </Card>
          <FooterToolbar style={{ width: '100%' }}>
            <Button onClick={() => router.goBack()}>返回</Button>
          </FooterToolbar>
        </Spin>
        <div>
          <Modal
            title="联系记录"
            visible={contactModal}
            onOk={this.contactSubmit}
            onCancel={this.hideModal}
            okText="确定"
            cancelText="关闭"
            width={494}
            destroyOnClose
          >
            <Form layout="horizontal">
              <FormItem label="联系方式" {...this.formItemLayoutModal}>
                {getFieldDecorator('entryContactType', {
                  rules: [{ required: true, message: '请选择' }],
                })(
                  <Select
                    placeholder="请选择"
                    style={{ width: '100%' }}
                    showSearch
                    optionFilterProp="children"
                  >
                    {dictCode.CONTACTWAY &&
                      dictCode.CONTACTWAY.map(item => (
                        <Option key={item.itemCode} value={item.itemCode}>
                          {item.itemName}
                        </Option>
                      ))}
                  </Select>
                )}
              </FormItem>
              <FormItem label="联系内容" {...this.formItemLayoutModal}>
                {getFieldDecorator('entryContent', {
                  rules: [{ required: true, message: '请输入' }],
                })(<TextArea rows={4} placeholder="请输入" />)}
              </FormItem>
            </Form>
          </Modal>
        </div>
        <div>
          <Modal
            title="办理备注"
            visible={remarkModal}
            onOk={this.remarkSubmit}
            onCancel={this.hideModal}
            okText="确定"
            cancelText="关闭"
            width={494}
            destroyOnClose
          >
            <Form layout="horizontal">
              {empContactList.insIdeFlag && empContactList.insIdeFlag === 1 ? (
                <div>
                  {!empContactList.insIdeName ? (
                    <FormItem label="缴费人员类别" {...this.formItemRemarkModal}>
                      {getFieldDecorator('insIde', {
                        rules: [{ required: true, message: '请选择' }],
                      })(
                        <Select
                          placeholder="请选择"
                          style={{ width: '100%' }}
                          showSearch
                          optionFilterProp="children"
                        >
                          {insIdeData
                            ? insIdeData.map(item => (
                                <Option key={item.ideId} value={item.ideId}>
                                  {item.ideName}
                                </Option>
                              ))
                            : null}
                        </Select>
                      )}
                    </FormItem>
                  ) : null}
                </div>
              ) : null}
              <FormItem label="备注" {...this.formItemRemarkModal}>
                {getFieldDecorator('hdlDesc', {
                  rules: [{ required: true, message: '请输入' }],
                })(<TextArea rows={4} placeholder="请输入" />)}
              </FormItem>
            </Form>
          </Modal>
        </div>
      </PageHeaderWrapper>
    );
  }
}

const BasicFormList = Form.create()(BasicForm);
export default BasicFormList;
